package top.milkbox.core;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

/**
 * Jesid连接池工具类
 */
public class UtilsJedisPool {
    // 声明连接池对象
    private static JedisPool jedisPool = null;

    // 静态代码块
    static {
        // 获取配置文件
        ClassLoader classLoader = UtilsJedisPool.class.getClassLoader(); // 获取当前的类加载器
        InputStream resourceAsStream = classLoader.getResourceAsStream("jedis.properties"); // 获取指定文件的字字符流
        // 加载配置文件
        Properties properties = new Properties();

        try {
            // 将配置文件加载进配置文件
            properties.load(resourceAsStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 创建并设置JedisPoolConfig对象
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(Integer.parseInt(properties.getProperty("maxTotal")));
        jedisPoolConfig.setMaxIdle(Integer.parseInt(properties.getProperty("maxIdle")));

        // 创建连接池对象
        jedisPool = new JedisPool(
                jedisPoolConfig,
                properties.getProperty("host"),
                Integer.parseInt(properties.getProperty("port"))
        );
    }

    /**
     * 获取一个jedis对象
     *
     * @return 返回一个jedis对象
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

}
